﻿using System;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using Sunny.UI;
using System.Collections.Generic;
using ThermalImagery.Business;
using ThermalImagery.Model;
using Leeder.Logger;
using ThermalImagery.Comm;

namespace ThermalImagery.Forms
{
    public partial class FrmRealTimeDetection : UIPage
    {
        /// <summary>
        /// 日志
        /// </summary>
        public LogOperate LogObj => Log.GetLogger(this.GetType());
        /// <summary>
        /// 热成像服务
        /// </summary>
        ThermAlarmBLL thermAlarmBLL = new ThermAlarmBLL();

        /// <summary>
        /// 实时消息集合
        /// </summary>
        List<NoticInfoModel> noticInfoList = new List<NoticInfoModel>();

        List<UILight> LightList = new List<UILight>();

        /// <summary>
        /// 判断窗体是否首次加载
        /// </summary>
        bool isLoad = true;

        public FrmRealTimeDetection()
        {
            InitializeComponent();
        }

        private void FrmRealTimeDetection_Load(object sender, EventArgs e)
        {
            if (GolbalVariable.SysSetup.DetectionMode == 1)
                labelDetectionMode.Text = "固定温度检测";
            else if (GolbalVariable.SysSetup.DetectionMode == 2)
                labelDetectionMode.Text = "温差检测";
            labelDetectionMode.ForeColor = Color.Blue;
            if (!isLoad)
                return;
            isLoad = false;
            string[] devices = new string[] { "IO卡", "红外相机" };
            for (int i = 0; i < 2; i++)
            {
                UILight light = new UILight();
                light.Size = new System.Drawing.Size(25, 25);
                light.OnColor = Color.Green;
                light.OnCenterColor = Color.Green;
                light.OffColor = Color.Red;
                light.OffCenterColor = Color.Red;
                light.State = UILightState.Off;
                UILabel label = new UILabel();
                label.Text = devices[i];
                label.Height = 30;
                uiFlowLayoutPanel1.Add(light);
                uiFlowLayoutPanel1.Add(label);
                LightList.Add(light);
            }
            uiLabel2.ForeColor = Color.Blue;
            uiLabel3.Text = "";
            uiProgressIndicator1.Visible = false;

            dgvAlarmInfo.AutoGenerateColumns = false;
            dgvAlarmInfo.AllowUserToAddRows = false;
            dgvAlarmInfo.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvAlarmInfo.ReadOnly = true;
            dgvAlarmInfo.AddColumn("通知时间", "NoticTime", 20);
            dgvAlarmInfo.AddColumn("实时消息", "NoticMsg", 80);
            dgvAlarmInfo.Columns[0].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss ";
            noticInfoList.Add(new NoticInfoModel { NoticTime = DateTime.Now, NoticMsg = "系统初始化..." });
            UpdateInfo(noticInfoList);
            string mess = Start();
            if (mess == "")
            {
                noticInfoList.Add(new NoticInfoModel { NoticTime = DateTime.Now, NoticMsg = "系统初始化完成！" });
                UpdateInfo(noticInfoList);
                LogObj.Info("系统初始化完成！");
            }
            else
            {
                noticInfoList.Add(new NoticInfoModel { NoticTime = DateTime.Now, NoticMsg = "系统初始化失败，失败原因：" + mess });
                UpdateInfo(noticInfoList);
                LogObj.Error("系统初始化失败，失败原因：" + mess);
            }
        }

        private void DeviceStateChanged(bool state, string mesg)
        {
            switch(mesg)
            {
                case "IO卡":
                    if (state)
                        LightList[0].State = UILightState.On;
                    else
                        LightList[0].State = UILightState.Off;
                    break;
                case "红外相机":
                    if (state)
                        LightList[1].State = UILightState.On;
                    else
                        LightList[1].State = UILightState.Off;
                    break;
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (btnStrat.Text == "开启相机")
            {
                string mess = Start();
                if (mess == "")
                {
                    noticInfoList.Add(new NoticInfoModel { NoticTime = DateTime.Now, NoticMsg = "系统初始化完成！" });
                    UpdateInfo(noticInfoList);
                    LogObj.Info("系统初始化完成！");
                }else
                {
                    noticInfoList.Add(new NoticInfoModel { NoticTime = DateTime.Now, NoticMsg = "系统初始化失败，失败原因：" + mess });
                    UpdateInfo(noticInfoList);
                    LogObj.Error("系统初始化失败，失败原因：" + mess);
                }
            }
            else
            {

                btnStrat.Text = "开启相机";
            }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private string Start()
        {
            thermAlarmBLL.AlarmEvent += FrmRealTimeDetection_changeEvent;
            thermAlarmBLL.CheckEvent += FrmRealTimeDetection_checkEvent;
            thermAlarmBLL.OnDeviceStateChanged += DeviceStateChanged;
            thermAlarmBLL.UiUpdateEvent += FrmRealTimeDetection_uiResetEvent;
            string mess = thermAlarmBLL.Init(this.RealPlayWnd);
            if (mess == "")
            {
                this.btnStrat.Text = "关闭相机";
            }
            else
            {
                UIMessageBox.ShowError(mess);
            }
            return mess;
        }


        int UIState = 0;
        /// <summary>
        /// 更新UI状态
        /// </summary>
        /// <param name="checkType">检测类型(0常态，1检测中，2检测结束)</param>
        /// <param name="result">检测结果</param>
        private void SetUIState(int checkType, string result)
        {
            if (checkType == 0 && UIState != 1)
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    uiLabel2.Text = "等待开始检测";
                    uiLabel2.ForeColor = Color.Blue;
                    uiLabel3.Text = "";
                    uiProgressIndicator1.Visible = false;
                    btnStratCheck.Enabled = true;
                    btnStrat.Enabled = true;
                    
                }));
            }
            else if (checkType == 1)
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    uiLabel2.Text = "检测中...";
                    uiLabel2.ForeColor = Color.Orange;
                    uiLabel3.Text = "";
                    uiLabel3.Visible = false;
                    uiProgressIndicator1.Visible = true;
                    btnStratCheck.Enabled = false;
                    btnStrat.Enabled = false;
                }));
            }
            else if (checkType == 2)
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    uiLabel2.Text = result;
                    uiLabel3.Text = result;
                    if (result == "OK")
                    {
                        uiLabel2.ForeColor = Color.Green;
                        uiLabel3.ForeColor = Color.Green;
                    }
                    else
                    {
                        uiLabel2.ForeColor = Color.Red;
                        uiLabel3.ForeColor = Color.Red;
                    }
                    uiLabel3.Visible = true;
                    uiProgressIndicator1.Visible = false;
                    btnStratCheck.Enabled = true;
                    btnStrat.Enabled = true;
                }));
            }
            UIState = checkType;
        }

        private void FrmRealTimeDetection_uiResetEvent()
        {
            SetUIState(0, "");
        }

        private void FrmRealTimeDetection_checkEvent(int checkType, string result)
        {
            SetUIState(checkType, result);
        }
        private void FrmRealTimeDetection_changeEvent(AlarmInfoModel model)
        {
            noticInfoList.Add(new NoticInfoModel {NoticTime = model.AlarmTime,NoticMsg= model.AlarmMsg});
            UpdateInfo(noticInfoList);
        }

        private void UpdateInfo(List<NoticInfoModel> infoList)
        {
            this.dgvAlarmInfo.Invoke(new Action(() => { this.dgvAlarmInfo.DataSource = noticInfoList.OrderByDescending(x => x.NoticTime).ToList(); }));
            if(infoList.Count >= 3000)
            {
                infoList.RemoveRange(0,2000);
            }
        }

        /// <summary>
        /// 手动检测
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStratCheck_Click(object sender, EventArgs e)
        {
            thermAlarmBLL.StartCheck(3);
        }

        /// <summary>
        /// 列表增加自动编号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            DataGridView dgv = (DataGridView)sender;
            //自动编号，与数据无关
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, dgv.RowHeadersWidth - 4, e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), dgv.RowHeadersDefaultCellStyle.Font, rectangle, dgv.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        /// <summary>
        /// 关闭窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmRealTimeDetection_FormClosing(object sender, FormClosingEventArgs e)
        {
            thermAlarmBLL.Close();
        }
    }
}
